import base64
import re

from django.core.cache import caches
from django.db.models import Q
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.utils import timezone

from app.captcha import Captcha
from app.models import Subject, Teacher, User
from django.http import JsonResponse

from app.utils import make_hash, get_verfir_code, gen_mobile_code, send_mobile_code


# TEL_PATTERN = re.compile(r'1[3-9]\d{9}')


def show_subjects(request):
    subjects = Subject.objects.all()
    context = {
        'subjects': subjects
    }
    return render(request, 'subjects.html', context)


def show_teachers(request):
    try:
        sno = request.GET.get('s_no', '')
        teachers = Teacher.objects.filter(subject__no=sno)
        subject = Subject.objects.filter(no=sno).first()
    except (KeyError, ValueError):
        return redirect('/')
    return render(request, 'teachers.html', locals())


def count(request):
    if not request.session.get('userid'):
        result = {'code': 10002, 'msg': '请先登录'}
    else:
        is_praise = request.path == '/praise/'
        try:
            tno = int(request.GET.get('tno', '0'))
            teacher = Teacher.objects.get(no=tno)
            if is_praise:
                teacher.good_count += 1
            else:
                teacher.bad_count += 1
            teacher.save()
            result = {'code': 10000, 'msg': '操作成功',
                      'count': teacher.good_count if is_praise else teacher.bad_count}
        except (ValueError, Teacher.DoesNotExist):
            result = {'code': 10001, 'msg': '操作失败'}
    return JsonResponse(result)


def login(request):
    msg = ''
    if request.method == 'GET':
        backurl = request.GET.get('backurl')
        backurl = base64.b64decode(backurl).decode() if backurl else '/'
    else:
        backurl = request.POST.get('backurl', '/')
        username = request.POST.get('username')
        password = request.POST.get('password')
        code_from_user = request.POST.get('captcha', '')
        code_from_img = request.POST.get('code', '')
        if username and password and code_from_user:
            if code_from_img == code_from_img:
                password = make_hash(password)
                user = User.objects.filter(Q(username=username) | Q(tel=username)).filter(password=password).first()
                if user:
                    delta = timezone.now() - user.last_visit
                    print(delta.days)
                    if delta.days > 0:
                        user.last_visit = timezone.now()
                        user.save(insert=False)
                    request.session['userid'] = user.userid
                    request.session['username'] = user.username
                    return redirect(backurl)
                else:
                    msg = 'username or password fail!'
            else:
                msg = '验证码错误'
        else:
            msg = '信息不全！！！'
    return render(request, 'login.html', locals())


def logout(request):
    request.session.flush()
    return redirect('/')


def captchar(request):
    code_txet = get_verfir_code()
    request.session['code'] = code_txet.lower()
    image = Captcha.instance().generate(code_txet)
    return HttpResponse(image, content_type='image/png')


def register(request):
    if request.method == 'GET':
        return render(request, 'register.html')
    else:
        username = request.POST.get('username')
        password = request.POST.get('password')
        repassword = request.POST.get('repassword')
        tel = request.POST.get('tel')
        if request.POST.get('modblecode') == request.POST.get('mobile_code'):
            if not User.objects.filter(username=username):
                if password == repassword:
                    user = User()
                    user.username = username
                    user.tel = tel
                    user.password = password
                    user.last_visit = timezone.now()
                    user.save()
                    return render(request, 'login.html')
                else:
                    msg = '密码不一致'
            else:
                msg = '用户名已存在'
        else:
            msg = '验证码错误'
        return render(request, 'register.html', locals())


def get_moblie_code(request, tel):
    if caches['default'].get(f'poll:app:block:{tel}'):
        data = {'code': 20004, 'msg': "请不要在60秒内重复发送验证码。"}
    else:
        code = gen_mobile_code()
        request.session['mobile_code'] = code.lower()
        result = send_mobile_code(tel, code)
        if result['error'] == 0:
            caches['default'].get(f'poll:app:block:{tel}', code, 60)
            caches['default'].get(f'poll:app:valid:{tel}', code, 600)
            data = {'code': 20000, 'msg': '短信发送成功！'}
        else:
            data = {'code': 20001, 'msg': '请重新发送短信验证码！'}

    return JsonResponse(data)
